
import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_with_title_dialog/common_edit_with_title_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_more_menu_dialog/common_more_menu_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_top_bar_menu_dialog/bean/common_top_bar_menu_list_item_bean.dart';
import 'package:e_reception_flutter/common_widgets/common_top_bar_menu_dialog/common_top_bar_menu_dialog.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/media_change_interval_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_detail_update.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_library_index_refresh_even.dart';
import 'package:e_reception_flutter/media_library/media_library_index/media_library_index_view_model.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_detail_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_settings_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/poster_detail_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_index_service.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_video_upload_service.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/building_index/building_index_diy_detail_page.dart';
import 'package:e_reception_flutter/ui/building_index/building_index_diy_list_response_bean.dart';
import 'package:e_reception_flutter/ui/building_index/refresh_diy_page_event.dart';
import 'package:e_reception_flutter/ui/index/index_view_model.dart';
import 'package:e_reception_flutter/ui/index/widgets/terminal_operations_dialog.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/bean/bg_terminal_music_list_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/bg_terminal_music_list_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/music_index_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/refresh_terminal_bg_music_list_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/event/play_file_update_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/terminal_detail_info_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/common_terminal_settings_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/set_terminal_state_type.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/new_terminal_list_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/set_terminal_status_menu_dialog.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/terminal_detail_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/widgets/operation_success_tips_dialog.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/widgets/terminal_detail_add_button_widget.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail_add_folder/terminal_detail_add_folder_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail_add_folder/terminal_detail_add_folder_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail_modify_order/terminal_detail_modify_order_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_details_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_one_details_page.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/click_back_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/menu_dialog.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:path_provider/path_provider.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_permission_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import '../../app_main.dart';
import 'bean/terminal_detail_response_bean.dart';

///单终端播放管理页面
class SingleTerminalMangePage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SingleTerminalMangePage";

  final String hsn;
  final String hsns;
  final String terminalName;
  final String position;
  final String cbid;
  final SetTerminalStateType currentState;
  final String onOffTime;
  final String onOffWeek;
  final int rcaid;
  final String autoOnOff;
  final ComAutoSwitchBean autoBean;

  const SingleTerminalMangePage({Key key, this.hsn, this.hsns, this.terminalName, this.position,
    this.cbid,
    this.currentState, this.onOffTime, this.onOffWeek, this.rcaid,
    this.autoOnOff, this.autoBean}) : super(key: key);

  @override
  _SingleTerminalMangePageState createState() => _SingleTerminalMangePageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context, String hsn, String hsns,
      String terminalName, String position, String cbid,
      SetTerminalStateType currentState, int rcaid,
      {String onOffTime, String onOffWeek, String autoOnOff, ComAutoSwitchBean autoBean}) {
    if (StringUtils.isEmpty(hsn)) {
      VgToastUtils.toast(context, "终端设备获取失败");
      return null;
    }
    return RouterUtils.routeForFutureResult(
      context,
      SingleTerminalMangePage(
        hsn: hsn,
        hsns: hsns,
        terminalName: terminalName,
        position: position,
        cbid: cbid,
        currentState: currentState,
        onOffTime: onOffTime,
        onOffWeek: onOffWeek,
        rcaid: rcaid,
        autoOnOff: autoOnOff,
        autoBean: autoBean,
      ),
      routeName: SingleTerminalMangePage.ROUTER,
    );
  }
}

class _SingleTerminalMangePageState
    extends BaseState<SingleTerminalMangePage> with SingleTickerProviderStateMixin{
  ValueNotifier<bool> _isShowAddButtonValueNotifier;
  TerminalDetailViewModel _viewModel;
  TerminalDetailAddFolderViewModel _addFolderViewModel;
  String _jumpToFolderId;
  ValueNotifier<String> _jumpToFolderIdValueNotifier;

  List<CommonTopBarMenuListItemBean> dialogMenuList;
  CommonTopBarMenuListItemBean dialogMenuValue;
  double _screenW;
  SetTerminalStateType _currentStateType;
  NewTerminalListViewModel _terminalListViewModel;
  String _onOffTime;
  String _onOffWeek;
  String _hsn;
  String _terminalName;
  String _autoOnOff;
  ComAutoSwitchBean _autoBean;
  int _rcaid;
  int _mediaChangeInterval = 15;

  BgTerminalMusicListViewModel _bgMusicViewModel;
  StreamSubscription _terminalBgMusicUpdateStreamSubscription;
  AnimationController _controller;

  Stream<double> _stream;
  double _opacityLevel = 1.0;
  ValueNotifier<double> _opacityLevelValueNotifier;
  IndexViewModel _indexViewModel;

  MediaLibraryVideoUploadService _mediaVideoUploadService;
  @override
  void initState() {
    super.initState();
    _mediaVideoUploadService = MediaLibraryVideoUploadService.getInstance();
    _screenW = ScreenUtils.screenW(AppMain.context);
    Future<String> interval = SharePreferenceUtil.getString(MediaLibraryIndexViewModel.MEDIA_CHANGE_INTERVAL);
    interval.then((value)  {
      if(StringUtils.isNotEmpty(value)){
        Map map = json.decode(value);
        ChangeIntervalBean bean = ChangeIntervalBean.fromMap(map);
        if(bean != null && bean.cpsecond > 0 && _mediaChangeInterval != bean.cpsecond){
          setState(() {
            _mediaChangeInterval = bean.cpsecond;
          });
        }
      }
    });
    VgEventBus.global.streamController.stream.listen((event) {
      if (event is MediaLibraryRefreshEven || event is MediaDetailUpdateEvent || (event is RefreshDiyPageEvent && (event?.isDelete??false))) {
        _viewModel.getTerminalPlayList();
      }
    });
    _hsn = widget?.hsn;
    _rcaid = widget?.rcaid;
    _terminalName = widget?.terminalName;
    _onOffTime = widget?.onOffTime;
    _onOffWeek = widget?.onOffWeek;
    _autoOnOff = widget?.autoOnOff;
    _autoBean = widget?.autoBean;
    _currentStateType = widget?.currentState;
    _viewModel = TerminalDetailViewModel(this, widget.hsn);
    _indexViewModel = IndexViewModel(this);
    _addFolderViewModel = TerminalDetailAddFolderViewModel(this, widget.hsn,);
    _terminalListViewModel = NewTerminalListViewModel(this);
    _isShowAddButtonValueNotifier = ValueNotifier(true);
    _jumpToFolderIdValueNotifier = ValueNotifier(null);
    _viewModel.getTerminalWithCache();
    _bgMusicViewModel = BgTerminalMusicListViewModel(this);
    String cacheKey = NetApi.GET_BG_MUSIC_LIST + (UserRepository.getInstance().getCacheKeySuffix()?? "")
        + widget?.hsn;
    _bgMusicViewModel.getBgMusicListOnLine(widget?.hsn, cacheKey, null);
    _terminalBgMusicUpdateStreamSubscription =
        VgEventBus.global.on<RefreshTerminalBgMusicListEvent>()?.listen((event) {
          _bgMusicViewModel.getBgMusicListOnLine(widget?.hsn, cacheKey, null);
        });

    dialogMenuList = [
      CommonTopBarMenuListItemBean(
          text: "刷脸优先",
          onTap: setMenu,
          value: 1
      ),
      CommonTopBarMenuListItemBean(
          text: "播放优先",
          onTap: setMenu,
          value: 2
      ),
      CommonTopBarMenuListItemBean(
          text: "人脸注册",
          onTap: setMenu,
          value: 3
      ),
      CommonTopBarMenuListItemBean(
          text: "仅播放",
          onTap: setMenu,
          value: 4
      ),
    ];
    dialogMenuValue = dialogMenuList.elementAt(0);

    _controller = AnimationController(duration: const Duration(seconds: 1), vsync: this);
    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        //动画从 controller.forward() 正向执行 结束时会回调此方法
        //重置起点
        _controller.reset();
        //开启
        _controller.forward();
      } else if (status == AnimationStatus.dismissed) {
        //动画从 controller.reverse() 反向执行 结束时会回调此方法
      } else if (status == AnimationStatus.forward) {
        //执行 controller.forward() 会回调此状态
      } else if (status == AnimationStatus.reverse) {
        //执行 controller.reverse() 会回调此状态
      }
    });

    _opacityLevelValueNotifier = new ValueNotifier(1.0);
    _stream = Stream.periodic(Duration(milliseconds: 500), (value) {
      _opacityLevel = _opacityLevel == 0 ? 1.0 : 0.0;
      return _opacityLevel;
    });

    _stream.listen((event) {
      _opacityLevelValueNotifier.value = event;
    });
  }

  void setMenu(CommonTopBarMenuListItemBean itemBean){
    dialogMenuValue = itemBean;
    setState(() {

    });
  }

  @override
  void dispose() {
    _isShowAddButtonValueNotifier?.dispose();
    _jumpToFolderIdValueNotifier?.dispose();
    _terminalBgMusicUpdateStreamSubscription?.cancel();
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: _toMainStackWidget(),
    );
  }

  Widget _toMainStackWidget() {
    return Stack(
      children: <Widget>[
        _toMainColumnWidget(),
        Visibility(
          visible: !UserRepository.getInstance().isSmartHomeCompany(),
          child: Align(
            alignment: Alignment.bottomCenter,
            child: ValueListenableBuilder(
                valueListenable: _isShowAddButtonValueNotifier,
                builder: (BuildContext context, bool isShow, Widget child) {
                  return AnimatedOpacity(
                    opacity: isShow ? 1 : 0,
                    duration: DEFAULT_ANIM_DURATION,
                    child: child,
                  );
                },
                child: TerminalDetailAddButtonWidget(
                  onTap: () async {
                    _addFolderViewModel.getList(context, _hsn, (size) async {
                      if(size < 1){
                        _processUpload();
                      }else{
                        String result =
                        await TerminalDetailAddFolderPage.navigatorPush(
                            context, _hsn,widget?.position);
                        if (StringUtils.isNotEmpty(result)) {
                          _jumpToFolderId = result;
                          _viewModel?.getTerminalPlayList();
                          VgEventBus.global.send(PlayFileUpdateEvent('播放文件更新'));
                        } else {
                          _jumpToFolderId = null;
                        }
                      }
                    });
                  },
                )),
          ),
        ),
      ],
    );
  }

  void _processUpload() async {
    List<String> resultList = await MatisseUtil.selectAll(
        context: context,
        isCanMixSelect: false,
        maxImageSize: 9,
        maxVideoSize: 1,
        videoMemoryLimit: 500*1024,
        videoDurationLimit: 10*60,
        videoDurationMinLimit: 10,
        maxAutoFinish: false,
        onRequestPermission: (msg)async{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: msg,
            cancelText: "取消",
            confirmText: "去授权",
          );
          if (result ?? false) {
            PermissionUtil.openAppSettings();
          }
        }
    );
    if (resultList == null || resultList.isEmpty) {
      return;
    }
    List<UploadMediaLibraryItemBean> _uploadList = List();
    Map<String, ImageInfo> _imageInfoMap = new Map();
    String localUrl = resultList[0];
    if (StringUtils.isEmpty(localUrl)) {
      return;
    }

    if(resultList.length == 1 && MatisseUtil.isVideo(localUrl)){
      //视频
      loading(true, msg: "视频处理中");
      handleVideo(localUrl, _uploadList);
    }else {
      if(resultList.length > 1){
        loading(true, msg: "图片处理中");
        int needClipCount = 0;
        int computeCount = 0;
        resultList.forEach((element) {
          FileImage image = FileImage(File(element));
          image.resolve(new ImageConfiguration())
              .addListener(
              new ImageStreamListener((ImageInfo info, bool _) async {
                _imageInfoMap[element] = info;
                double width = info.image.width + 0.0;
                double height = info.image.height + 0.0;
                if (width / height != 9.0 / 16.0) {
                  needClipCount++;
                }
                computeCount++;
                if (computeCount == resultList.length) {
                  loading(false);
                  if(needClipCount > 0){
                    bool result =
                    await CommonConfirmCancelDialog.navigatorPushDialog(context,
                        title: "提示",
                        content: "检测到${needClipCount}张图片长宽比不符合16:9，是否逐个裁剪处理？",
                        cancelText: "保持原比例",
                        confirmText: "去裁剪",
                        confirmBgColor: ThemeRepository.getInstance()
                            .getPrimaryColor_1890FF());
                    //去裁剪
                    if(result == null){
                      RouterUtils.pop(context);
                      return;
                    }
                    if (result ?? false) {
                      handleImage(localUrl, resultList, _uploadList);
                    } else {
                      //保持原图比例
                      resultList.forEach((element) {
                        _uploadList.add(UploadMediaLibraryItemBean(
                          localUrl: element,
                          mediaType: MediaType.image,
                          folderWidth: _imageInfoMap[element].image.width,
                          folderHeight: _imageInfoMap[element].image.height,));
                      });


                      String result = await MediaSettingsPage.navigatorPushString(
                          context, _uploadList[0],
                          singleflg: true,
                          needUpload: true,
                          currentHsn: widget?.hsn,
                          hsns: widget?.hsn,
                          itemList: _uploadList, branchname: widget?.position);
                      // if (StringUtils.isNotEmpty(result)) {
                      //   RouterUtils.pop(context);
                      // }
                    }
                  }else{
                    //保持原图比例
                    resultList.forEach((element) {
                      _uploadList.add(UploadMediaLibraryItemBean(
                        localUrl: element,
                        mediaType: MediaType.image,
                        folderWidth: _imageInfoMap[element].image.width,
                        folderHeight: _imageInfoMap[element].image.height,));
                    });

                    String result = await MediaSettingsPage.navigatorPushString(
                        context, _uploadList[0],
                        singleflg: true,
                        needUpload: true,
                        currentHsn: widget?.hsn,
                        hsns: widget?.hsn,
                        itemList: _uploadList, branchname: widget?.position);
                    // if (StringUtils.isNotEmpty(result)) {
                    //   RouterUtils.pop(context);
                    // }
                  }

                }
              }));
        });
      }else{
        handleImage(localUrl, resultList, _uploadList);
      }


    }
  }

  ///处理视频的逻辑
  void handleVideo(String localUrl, List<UploadMediaLibraryItemBean> _uploadList)async{
    //视频
    UploadMediaLibraryItemBean item = UploadMediaLibraryItemBean(
      localUrl: localUrl, mediaType: MediaType.video,);

    File file = File(item.localUrl);
    Directory rootPath = await getTemporaryDirectory();
    Directory tempDirectory = new Directory('${rootPath.path}/imageTemp');
    if (!tempDirectory.existsSync()) {
      tempDirectory.createSync();
    }

    String tmpVideoCover = await VideoThumbnail.thumbnailFile(
      video: item.localUrl,
      thumbnailPath: tempDirectory?.path,
      imageFormat: ImageFormat.JPEG,
      maxWidth: 1920,
      quality: 100,
    );
    item.videoLocalCover = tmpVideoCover;
    item.videoLocalCover = tmpVideoCover;
    //
    VideoPlayerController videoController = VideoPlayerController.file(file);
    await videoController.initialize();
    item.videoDuration = videoController?.value?.duration?.inSeconds;
    item.folderWidth = videoController?.value?.size?.width?.floor();
    item.folderHeight = videoController?.value?.size?.height?.floor();
    item.folderStorage = file.lengthSync();

    _uploadList.add(item);
    videoController.dispose();
    loading(false);
    String result = await MediaSettingsPage.navigatorPushString(context, _uploadList[0],
        singleflg: true, needUpload:true, currentHsn: widget?.hsn, hsns: widget?.hsn,
        itemList: _uploadList, branchname: widget?.position);
    // if(StringUtils.isNotEmpty(result)){
    //   RouterUtils.pop(context);
    // }
  }

  ///处理图片
  void handleImage(String localUrl, List<String> resultList, List<UploadMediaLibraryItemBean> _uploadList){
    //图片
    List<Future> taskList = resultList.reversed.map((element) {
      FileImage image = FileImage(File(element));
      // 预先获取图片信息
      image
          .resolve(new ImageConfiguration())
          .addListener(new ImageStreamListener((ImageInfo info,
          bool _) async {
        double width = info.image.width + 0.0;
        double height = info.image.height + 0.0;

        if (width / height != 9.0 / 16.0) {
          String clipPath = await MatisseUtil.clipOneImage(context,
              path: element, scaleX: 9, scaleY: 16,
              isCanMixRadio: true,
              topLeftWidget: _topLeftWidget(),
              keepRadioWidget: _keepWidget(info, element, _uploadList, resultList.length),
              rightTopClipWidget: _topRightWidget(),
              onRequestPermission: (msg)async{
                bool result =
                await CommonConfirmCancelDialog.navigatorPushDialog(context,
                  title: "提示",
                  content: msg,
                  cancelText: "取消",
                  confirmText: "去授权",
                );
                if (result ?? false) {
                  PermissionUtil.openAppSettings();
                }
              }
          );
          if(clipPath == null){
            return;
          }
          if (StringUtils.isNotEmpty(clipPath)) {
            FileImage clipImage = FileImage(File(clipPath));
            clipImage
                .resolve(new ImageConfiguration())
                .addListener(new ImageStreamListener((ImageInfo info, bool _) async {
              _uploadList.add(UploadMediaLibraryItemBean(
                localUrl: clipPath,
                mediaType: MediaType.image,
                folderWidth: info.image.width,
                folderHeight: info.image.height,
              ));
              if (_uploadList.length == resultList.length) {
                String result = await MediaSettingsPage
                    .navigatorPushString(context, _uploadList[0],
                    singleflg: true,
                    needUpload: true,
                    currentHsn: widget?.hsn,
                    hsns: widget?.hsn,
                    itemList: _uploadList, branchname: widget?.position);
                // if (StringUtils.isNotEmpty(result)) {
                //   RouterUtils.pop(context);
                // }
              }
            }));



          } else {
            if (_uploadList.length == resultList.length) {
              //判断是否是重复数据
              int count = 0;
              _uploadList.forEach((element) {
                if(localUrl == element.localUrl){
                  count++;
                }
              });
              if(count == 0){
                _uploadList.add(UploadMediaLibraryItemBean(
                  localUrl: localUrl,
                  mediaType: MediaType.image,
                  folderWidth: info.image.width,
                  folderHeight: info.image.height,));
              }
            }
          }
        }

        else {
          _uploadList.add(UploadMediaLibraryItemBean(
            localUrl: element,
            mediaType: MediaType.image,
            folderWidth: info.image.width,
            folderHeight: info.image.height,));

          if (_uploadList.length == resultList.length) {
            String result = await MediaSettingsPage.navigatorPushString(
                context, _uploadList[0],
                singleflg: true,
                needUpload: true,
                currentHsn: widget?.hsn,
                hsns: widget?.hsn,
                itemList: _uploadList, branchname: widget?.position);
            // if (StringUtils.isNotEmpty(result)) {
            //   RouterUtils.pop(context);
            // }
          }
        }
      }));

      return new Future(() {
        print(element);
      });
    }).toList();

  }

  Widget _topLeftWidget(){
    return ClickAnimateWidget(
      child: Container(
        width: 40,
        height: 44,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.only(left: 15.6),
        child: Image.asset(
          "images/top_bar_back_ico.png",
          width: 9,
          color: VgColors.INPUT_BG_COLOR,
        ),
      ),
      scale: 1.4,
      onClick: () {
        // VgNavigatorUtils.pop(context);
        FocusScope.of(context).requestFocus(FocusNode());
        Navigator.of(context).maybePop();
      },
    );
  }

  Widget _keepWidget(ImageInfo info, String localUrl, List<UploadMediaLibraryItemBean> _uploadList, int totalSize){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        if(StringUtils.isNotEmpty(localUrl)){
          Navigator.of(context).pop();
          _uploadList.add(UploadMediaLibraryItemBean(
            localUrl: localUrl,
            mediaType: MediaType.image,
            folderWidth: info.image.width,
            folderHeight: info.image.height,));
          // bool result = await MediaSettingsPage.navigatorPush(context, _uploadList[0]);
          // if(result??false){
          //   _viewModel?.refreshMultiPage();
          // }
          if(_uploadList.length == totalSize){
            String result = await MediaSettingsPage.navigatorPushString(context, _uploadList[0],
                singleflg: true, needUpload:true,  currentHsn: widget?.hsn,
                hsns: widget?.hsn, itemList: _uploadList, branchname: widget?.position);
            // if(StringUtils.isNotEmpty(result)) {
            //   RouterUtils.pop(context);
            // }
          }

        }
      },
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 5, vertical: 22),
        child: Container(
          height: 21.5,
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
          alignment: Alignment.center,
          child: Text(
            "原始比例",
            style: TextStyle(color: Color(0xffaaaaaa), fontSize: 12, height: Platform.isIOS ? 1.2 : 1.15),
          ),
        ),
      ),
    );
  }

  Widget _topRightWidget(){
    return Container(
      height: 23,
      width: 48,
      alignment: Alignment.center,
      margin: EdgeInsets.only(left: 15, right: 15, top: 11, bottom: 10),
      decoration: BoxDecoration(
        color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        borderRadius: BorderRadius.circular(11.5),
      ),
      child: Text(
        "确定",
        style: TextStyle(
            fontSize: 12,
            color: Colors.white
        ),
      ),
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        _toTopBarWidget(),
        _toMusicWidget(),
        _toPlayStatisticsWidget(),
        _toUploadView(),
        Expanded(
          child: ValueListenableBuilder(
              valueListenable: _viewModel?.statusTypeValueNotifier,
              builder:
                  (BuildContext context, PlaceHolderStatusType value, Widget child) {
                return VgPlaceHolderStatusWidget(
                  loadingStatus: value == PlaceHolderStatusType.loading,
                  errorStatus: value == PlaceHolderStatusType.error,
                  emptyStatus: value == PlaceHolderStatusType.empty,
                  errorOnClick: () => _viewModel
                      .getTerminalPlayList(),
                  loadingOnClick: () => _viewModel
                      .getTerminalPlayList(),
                  child: child,
                );
              },
              child: _toGridListWidget()),
        )
      ],
    );
  }

  ///标题栏
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      centerWidget: _toCenterWidget(context),
      rightWidget: _toDeleteWidget(),
    );
  }

  ///音乐
  Widget _toMusicWidget(){
    return ValueListenableBuilder(
        valueListenable: _bgMusicViewModel.musicListAndFlagValueNotifier,
        builder:
            (BuildContext context, MusicListDataBean listDataBean, Widget child) {
          return GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: (){
                MusicIndexPage.navigatorPush(context, widget?.terminalName, widget?.hsn, widget?.hsns);
              },
              child: Container(
                margin: EdgeInsets.only(left: 15, top: 6, right: 15),
                height: 34,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                      begin: Alignment.centerLeft,
                      end: Alignment.centerRight,
                      colors: [
                        Color(0xFFCA45FF).withOpacity(0.2),
                        Color(0xFF0365FF).withOpacity(0.2),
                      ]
                  ),
                  borderRadius: BorderRadius.all(Radius.circular(17)),
                ),
                alignment: Alignment.centerLeft,
                child: Row(
                  children: [
                    SizedBox(width: 5,),
                    _toMusicLogoWidget(listDataBean),
                    SizedBox(width: 6.5,),
                    _toMusicNameWidget(listDataBean),
                    Spacer(),
                    _toMusicStatusWidget(listDataBean),
                    SizedBox(width: 12,),
                    Image.asset(
                      "images/icon_arrow_right_grey.png",
                      width: 6,
                    ),
                    SizedBox(width: 12,),
                  ],
                ),
              )
          );
        }
    );

  }

  ///音乐logo布局
  Widget _toMusicLogoWidget(MusicListDataBean listDataBean){
    String asset = "images/icon_music_stop.png";
    if(listDataBean != null && (listDataBean?.musicList?.isNotEmpty??false) && (listDataBean?.isOpen()??false)){
      asset = "images/icon_music_play.png";
    }
    if((listDataBean?.isOpen()??false) && (listDataBean?.musicList?.isNotEmpty??false)){
      _controller.forward();
      return RotationTransition(
        alignment: Alignment.center,
        turns: _controller,
        child: Image.asset(
          asset,
          width: 24,
          height: 24,
        ),
      );
    }
    return Image.asset(
      asset,
      width: 24,
      height: 24,
    );
  }

  ///音乐名布局
  Widget _toMusicNameWidget(MusicListDataBean listDataBean){
    String content = "-";
    Color textColor = ThemeRepository.getInstance().getTextColor_D0E0F7();
    if(listDataBean == null || (listDataBean?.musicList?.isEmpty??true)){
      content = "暂无背景音乐";
      textColor = ThemeRepository.getInstance().getHintGreenColor_5E687C();
    }else{
      if(!(listDataBean?.isOpen()??false)){
        //未打开背景音乐
        content = "背景音乐";
      }else{
        //打开了背景音乐
        if(listDataBean.musicList.length == 1){
          content = listDataBean.musicList.elementAt(0)?.mname??"";
        }else{
          content = "${listDataBean.musicList.length}首背景音乐";
        }
      }
    }

    return Text(
      content,
      style: TextStyle(
        fontSize: 12,
        color: textColor,
      ),
    );
  }

  ///音乐状态
  Widget _toMusicStatusWidget(MusicListDataBean listDataBean){
    if(listDataBean == null || (listDataBean?.musicList?.isEmpty??true)){
      return SizedBox();
    }
    String text = "已关闭";
    Color textColor = ThemeRepository.getInstance().getMinorRedColor_F95355();
    if(listDataBean?.isOpen()??false){
      text = "已开启";
      textColor = Color(0XFF00C6C4);
    }
    return Text(
      text,
      style: TextStyle(
        fontSize: 12,
        color: textColor,
      ),
    );
  }


  Widget _toDeleteWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () async{
        TerminalDetailInfoPage.navigatorPush(context, _hsn, popflg: true, router: SingleTerminalMangePage.ROUTER);
      },
      child: Container(
        padding: EdgeInsets.only(top: 13, bottom: 13, left: 13),
        child: Text(
          "属性",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
            fontSize: 13,
          ),
        ),
      ),
    );
  }

  ///标题内容布局
  Widget _toCenterWidget(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        // CommonTopBarMenuDialog.navigatorPushDialog(context, dialogMenuList, dialogMenuValue?.value);
        // if(_currentStateType == SetTerminalStateType.off){
        //   return;
        // }
        SetTerminalStatusMenuDialog.navigatorPushDialog(context,
                (currentState){
              _onOpen?.call(currentState);
            },
                (currentState){
              _screenOff?.call(currentState);
            },
                (currentState){
              _off?.call(currentState);
            },
                (time){
              setState(() {
                if(StringUtils.isNotEmpty(time)){
                  _onOffTime = time;
                }
              });
            },
            _currentStateType,
            _onOffTime,
            _onOffWeek,
            _hsn,
            _rcaid,
            _terminalName,
            _autoOnOff,
            _autoBean,
            weekChange: (week){
              setState(() {
                if(StringUtils.isNotEmpty(week)){
                  _onOffWeek = week;
                }
              });
            },
            autoOnOffChange: (onOff){
              setState(() {
                _autoOnOff = onOff;
              });
            }
        );
      },
      child: Container(
        constraints: BoxConstraints(maxWidth: ScreenUtils.screenW(context)),
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Text(
                _terminalName ?? "-",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color:
                    ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                    fontSize: 17,
                    height: 1.2,
                    fontWeight: FontWeight.w600),
              ),
              _toStatusWidget(),
              // _toSwitchWidget(),
            ],
          ),
        ),
      ),
    );
  }


  void _onOpen(SetTerminalStateType currentState){
    print("开机");
    // if(widget?.currentState == currentState){
    //   return;
    // }
    _terminalListViewModel.terminalOffScreen(context, _hsn, "00", callback: (){
      setState(() {
        _currentStateType = SetTerminalStateType.open;
      });
    });
  }

  void _screenOff(SetTerminalStateType currentState){
    print("息屏开机");
    // if(widget?.currentState == currentState){
    //   return;
    // }
    _terminalListViewModel.terminalOffScreen(context, _hsn, "01", callback: (){
      setState(() {
        _currentStateType = SetTerminalStateType.screenOff;
      });
    });
  }

  void _off(SetTerminalStateType currentState){
    print("关机");
    _terminalListViewModel.terminalOff(context, _hsn, callback: (){
      setState(() {
        _currentStateType = SetTerminalStateType.off;
      });
    });
  }


  String getTerminalStatus(){
    if(_currentStateType == SetTerminalStateType.off){
      return "已关机";
    }
    if(_currentStateType == SetTerminalStateType.open){
      return "正常开机";
    }
    if(_currentStateType == SetTerminalStateType.screenOff){
      return "已关机";
      // return "息屏开机";
    }
    return "已关机";
  }

  Widget _toStatusWidget(){
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          getTerminalStatus()??"未知",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
              color:(_currentStateType == SetTerminalStateType.off)
                  ?ThemeRepository.getInstance().getTextMainColor_D0E0F7()
                  :ThemeRepository.getInstance().getHintGreenColor_00C6C4(),
              fontSize: 10,
              height: 1.2
          ),
        ),
        Visibility(
          visible: !(_currentStateType == SetTerminalStateType.off),
          child: Row(
            children: [
              SizedBox(width: 5,),
              Image(
                image: AssetImage("images/icon_shape_arrow_down.png"),
                width: 7,
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _toSwitchWidget() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        SizedBox(width: 6,),
        Text(
          dialogMenuValue?.text ?? "-",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
              color: ThemeRepository.getInstance().getMinorYellowColor_FFB714(),
              fontSize: 10,
              height: 1.2
          ),
        ),
        Transform.translate(
          offset: Offset(-3, 0),
          child: Icon(
            Icons.arrow_drop_down,
            size: 16,
            color: ThemeRepository.getInstance().getMinorYellowColor_FFB714(),
          ),
        )
      ],
    );
  }

  ///播放统计布局
  Widget _toPlayStatisticsWidget(){
    return ValueListenableBuilder(
      valueListenable: _viewModel.picListValueNotifier,
      builder: (BuildContext context, TerminalDetailDataBean detailDataBean, Widget child){
        String statisticsString;
        if(detailDataBean?.list != null && detailDataBean.list.isNotEmpty){
          int allPlayTime = 0;
          detailDataBean.list.forEach((element) {
            if(!element.isIndex()){
              if(element.isVideo()){
                allPlayTime += int.parse(element.videotime);
              }else{
                allPlayTime += _mediaChangeInterval;
              }
            }
          });
          int minute = allPlayTime~/60;
          int second = allPlayTime - (60 * minute);
          String minuteString = minute>0? (minute.toString()+"分钟"):"";
          String secondString = second>0? (second.toString()+"秒"):"";
          statisticsString = "今日播放共${detailDataBean.list.length}个文件，每轮需${minuteString}${secondString}";
        }else{
          statisticsString = "今日播放共0个文件，每轮需0分钟0秒";
        }
        return Container(
          height: 45,
          padding: EdgeInsets.symmetric(horizontal: 15),
          child: Row(
            children: [
              Text(
                statisticsString,
                style: TextStyle(
                    fontSize: 12,
                    color: ThemeRepository.getInstance().getHintGreenColor_5E687C()
                ),
              ),
              Spacer(),
              GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () async{
                  bool result = await TerminalDetailModifyOrderPage.navigatorPush(context, _hsn, widget?.position);
                  if(result ?? false){
                    _viewModel.getTerminalPlayList();
                  }
                },
                child: Visibility(
                  visible: (detailDataBean?.list != null && detailDataBean.list.length >1),
                  child: Container(
                    padding: EdgeInsets.only(top: 13, bottom: 13, left: 13),
                    child: Row(
                      children: [
                        Image.asset(
                          "images/icon_play_setting.png",
                          width: 12,
                        ),
                        SizedBox(width: 6,),
                        Text(
                          "播放序列",
                          style: TextStyle(
                              fontSize:12,
                              color: ThemeRepository.getInstance().getPrimaryColor_1890FF()
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              )
            ],
          ),
        );
      },
    );

  }

  ///上传布局
  Widget _toUploadView(){
    return StreamBuilder<List<UploadMediaLibraryItemBean>>(
        stream: _mediaVideoUploadService?.uploadServiceStream?.stream,
        initialData: _mediaVideoUploadService?.getUploadingInfoList(widget?.hsn),
        builder: (context, AsyncSnapshot<List<UploadMediaLibraryItemBean>> snapshot) {
          List<UploadMediaLibraryItemBean> infoList = snapshot?.data;
          if(infoList == null || infoList.isEmpty){
            return Container();
          }else{
            UploadMediaLibraryItemBean firstItem = infoList.first;
            double padding = (infoList.length > 1)?12:15;
            return Container(
                padding: EdgeInsets.only(left: 12, right: 12, top: padding, bottom: padding),
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                height: 67,
                child: Column(children: <Widget>[
                  Row(
                    children: <Widget>[
                      _toCoverWidget(infoList),
                      SizedBox(
                        width: 5,
                      ),
                      Text("正在上传视频",
                          style: TextStyle(color: Color(0xFF999999), fontSize: 13)),
                      Spacer(),
                      GestureDetector(
                        child: Container(
                          padding: const EdgeInsets.only(left: 10,right: 10),
                          height: 24,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(
                                color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                                width: 0.5),
                          ),
                          child: Text(
                            "终止",
                            style: TextStyle(
                              fontSize: 13,
                              color: Colors.white,
                            ),
                          ),
                        ),
                        onTap: () async{
                          bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
                              title: "提示",
                              content: "确定终止上传视频？",
                              cancelText: "取消",
                              confirmText: "确定",
                              confirmBgColor: ThemeRepository.getInstance()
                                  .getMinorRedColor_F95355());
                          if (result ?? false) {
                            if(infoList.length > 1){
                              _mediaVideoUploadService?.cancelAll(firstItem?.id);
                            }else{
                              _mediaVideoUploadService?.cancelUpload(firstItem?.id, firstItem?.localUrl,);
                            }
                          }
                          // _viewModel.uploadModel!.removeCurrentBean();
                        },
                      )
                    ],
                  ),
                  SizedBox(
                    height: 5,
                  ),
                  Container(
                    height: 2,
                    child: StreamBuilder<UploadMediaLibraryItemBean>(
                      stream: _mediaVideoUploadService?.uploadingStreamMap[firstItem?.id]?.stream,
                      initialData: _mediaVideoUploadService?.getCurrentUploadingInfoFromTerminal(widget?.hsn, firstItem?.id),
                      builder: (context, AsyncSnapshot<UploadMediaLibraryItemBean> snapshot){
                        UploadMediaLibraryItemBean item = snapshot?.data;
                        return LinearProgressIndicator(
                            value: (item?.progress ?? 0)/100.0,

                            backgroundColor: Color(0xFFCEE0F9),
                            valueColor:
                            new AlwaysStoppedAnimation<Color>(Color(0xFF179ECE)));
                      },

                    ),
                  ),
                ]));
          }
        }
    );
  }

  ///根据上传视频的数据获取封面布局
  Widget _toCoverWidget(List<UploadMediaLibraryItemBean> infoList){
    if(infoList.length == 1){
      UploadMediaLibraryItemBean item = infoList.elementAt(0);
      return Container(
        width: 30,
        height: 30,
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: <Widget>[
            item?.videoLocalCover != null
                ? Image.file(
              File(item?.videoLocalCover??""),
              width: 30,
              height: 30,
              cacheWidth: 30,
              cacheHeight: 30,
              fit: BoxFit.cover,
            )
                : Container(
              width: 30,
              height: 30,
            ),
            Image.asset(
              "images/icon_smart_home_video_play.png",
              width: 10,
              height: 10,
            )
          ],
        ),
      );
    }else{
      UploadMediaLibraryItemBean firstItem = infoList.elementAt(0);
      UploadMediaLibraryItemBean secondItem = infoList.elementAt(1);
      return Stack(
        children: [
          Container(
            width: 30,
            height: 30,
            child: Stack(
              alignment: AlignmentDirectional.center,
              children: <Widget>[
                secondItem?.videoLocalCover != null
                    ? Image.file(
                  File(secondItem?.videoLocalCover??""),
                  width: 30,
                  height: 30,
                  cacheWidth: 30,
                  cacheHeight: 30,
                  fit: BoxFit.cover,
                )
                    : Container(
                  width: 30,
                  height: 30,
                ),
                Image.asset(
                  "images/icon_smart_home_video_play.png",
                  width: 10,
                  height: 10,
                )
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 6, top: 6),
            child: Container(
              width: 30,
              height: 30,
              child: Stack(
                alignment: AlignmentDirectional.center,
                children: <Widget>[
                  firstItem?.videoLocalCover != null
                      ? Image.file(
                    File(firstItem?.videoLocalCover??""),
                    width: 30,
                    height: 30,
                    cacheWidth: 30,
                    cacheHeight: 30,
                    fit: BoxFit.cover,
                  )
                      : Container(
                    width: 30,
                    height: 30,
                  ),
                  Image.asset(
                    "images/icon_smart_home_video_play.png",
                    width: 10,
                    height: 10,
                  )
                ],
              ),
            ),
          ),
        ],
      );
    }
  }

  ///数据网格列表
  Widget _toGridListWidget(){
    return ValueListenableBuilder(
      valueListenable: _viewModel?.picListValueNotifier,
      builder: (BuildContext context, TerminalDetailDataBean detailDataBean, Widget child){
        return NotificationListener(
          onNotification: (Notification notification) {
            if (notification is ScrollStartNotification) {
              _isShowAddButtonValueNotifier?.value = false;
            }
            if (notification is ScrollUpdateNotification) {
              _isShowAddButtonValueNotifier?.value = false;
            }
            if (notification is ScrollEndNotification) {
              _isShowAddButtonValueNotifier?.value = true;
            }
            return false;
          },
          child: ScrollConfiguration(
              behavior: MyBehavior(),
              child: GridView.builder(
                padding: EdgeInsets.only(
                    left: 15,
                    right: 15,
                    bottom: getNavHeightDistance(context)),
                itemCount: detailDataBean?.list?.length ?? 0,
                physics: BouncingScrollPhysics(),
                shrinkWrap: true,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  mainAxisSpacing: 12,
                  crossAxisSpacing: 8,
                  childAspectRatio: 111 / 215,
                ),
                itemBuilder: (BuildContext context, int index) {
                  return _toGridItemWidget(context, detailDataBean?.list?.elementAt(index));
                },
              )),
        );
      },
    );
  }

  ///item布局
  Widget _toGridItemWidget(BuildContext context, TerminalDetailListItemBean itemBean){
    double width = (_screenW - 30 - 24)/3;
    double height = (195*width)/111;
    double fixScale = width/height;
    BoxFit boxFit = BoxFit.contain;
    int imgWidth = 1;
    int imgHeight = 1;
    if(StringUtils.isNotEmpty(itemBean?.getPicSize())){
      imgWidth = int.parse(itemBean?.getPicSize()?.split("*")[0]);
      imgHeight = int.parse(itemBean?.getPicSize()?.split("*")[1]);
    }
    double scale = imgWidth/imgHeight;
    if(fixScale > scale){
      boxFit = BoxFit.cover;
    }else{
      boxFit = BoxFit.contain;
    }
    return Column(
      children: [
        ClickBackgroundWidget(
          onTap: (){
            _onTap(itemBean);
          },
          onLongPress: (detail){
            return MenuDialogUtils.showMenuDialog(context: context,longPressDetails: detail,itemMap: _getMenuMap(context, itemBean));
          },
          child: ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: Container(
              height: height,
              width: width,
              decoration: BoxDecoration(color: Colors.black),
              child: Stack(
                fit: StackFit.expand,
                children: <Widget>[
                  (itemBean?.isSmart() ?? false)
                      ? _toSmartHomeWidget(fixScale, width, height, itemBean)
                      : VgCacheNetWorkImage(
                    itemBean?.getCoverUrl() ?? "",
                    fit: boxFit,
                    imageQualityType: ImageQualityType.middleDown,
                  ),
                  Center(
                    child: Offstage(
                        offstage: !(itemBean?.isVideo() ?? false),
                        child: Opacity(
                          opacity: 0.5,
                          child: Image.asset(
                            "images/video_play_ico.png",
                            width: 52,
                          ),
                        )),
                  ),
                  Positioned(
                    top: 7,
                    left: 7,
                    child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () async {
                        VgEventBus.global.send(new UpdateHomePageEventMonitor());
                        if (_currentStateType == SetTerminalStateType.off) {
                          OperationSuccessTipsDialog.navigatorPushDialog(context,
                              title: "设备已关机，无法设置重复播放");
                          return;
                        }
                        if ("00" == itemBean.stopflg) {
                          bool result =
                          await TerminalOperationsDialog.navigatorPushDialog(
                              context,
                              title: "循环播放当前文件？",
                              cancelText: "取消",
                              confirmText: "确定",
                              confirmBgColor: ThemeRepository.getInstance()
                                  .getPrimaryColor_1890FF());
                          if (result ?? false) {
                            itemBean.hsn = widget?.hsn;
                            itemBean.editStopFlg =
                            ("01" == itemBean.stopflg) ? "02" : "01";
                            _onRepeat.call(itemBean);
                          }
                        } else {
                          itemBean.hsn = widget?.hsn;
                          itemBean.editStopFlg =
                          ("01" == itemBean.stopflg) ? "02" : "01";
                          _onRepeat.call(itemBean);
                        }
                      },
                      child: Container(
                        width: 50,
                        height: 50,
                        alignment: Alignment.topLeft,
                        child: _toRepeatWidget(itemBean),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        Expanded(
          child: Container(
            margin: const EdgeInsets.symmetric(vertical: 4),
            alignment: Alignment.topLeft,
            child: Text(
              itemBean?.getPlayTimeString(),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: ThemeRepository.getInstance()
                    .getTextMinorGreyColor_808388(),
                fontSize: 11,
              ),
            ),
          ),
        ),
      ],
    );
  }

  ///重复图标布局
  Widget _toRepeatWidget(TerminalDetailListItemBean itemBean) {
    return (("01" == itemBean?.stopflg ?? "") && !(_currentStateType == SetTerminalStateType.off))
        ? ValueListenableBuilder(
        valueListenable: _opacityLevelValueNotifier,
        builder: (BuildContext context, double opacityLevel, Widget child) {
          return AnimatedOpacity(
            opacity: opacityLevel,
            duration: Duration(milliseconds: 500),
            curve: Curves.linear,
            child: SizedBox(
              width: 20,
              height: 20,
              child: Image.asset(
                "images/icon_repeat.png",
                width: 20,
                height: 20,
              ),
            ),
          );
        })
        : SizedBox(
      width: 20,
      height: 20,
      child: Image.asset(
        "images/icon_repeat_empty.png",
        width: 20,
        height: 20,
      ),
    );
  }

  void _onRepeat(TerminalDetailListItemBean itemBean){
    if (StringUtils.isEmpty(itemBean?.picid)) {
      VgToastUtils.toast(context, "资源获取失败");
      return;
    }
    if(itemBean.isIndex()){
      _indexViewModel?.repeatBuildingIndex(context, itemBean.hsn,
          itemBean.buildingIndexId, itemBean.stopflg,
          callback: (){
            _viewModel.getTerminalPlayList();
          }
      );
    }else if(itemBean.isSmart()){
      _indexViewModel?.repeatSmartHome(context, itemBean.hsn,
          itemBean.rasid, itemBean.stopflg,
          callback: (){
            _viewModel.getTerminalPlayList();
          });
    }else{
      _indexViewModel?.repeatPlay(context, itemBean.picid, itemBean.editStopFlg,
          itemBean.id, itemBean.hsn,
          callback: (){
            _viewModel.getTerminalPlayList();
          });
    }
  }

  Widget _toSmartHomeWidget(double fixScale, double containerWidth, double containerHeight,TerminalDetailListItemBean itemBean) {
    if (itemBean?.picList == null || (itemBean?.picList?.length ?? 0) == 0) {
      return Container();
    }
    if ((itemBean?.picList?.length ?? 0) == 1) {
      return _toSingleImageWidget(fixScale, itemBean);
    } else if ((itemBean?.picList?.length  ?? 0) == 2) {
      return _toTwoImageWidget(containerWidth, containerHeight, itemBean);
    } else if ((itemBean?.picList?.length  ?? 0) == 3) {
      return _toThreeImageWidget(containerWidth, containerHeight, itemBean);
    } else {
      //4个及以上
      return _toFourImageWidget(containerWidth, containerHeight, itemBean);
    }
  }

  ///单图
  Widget _toSingleImageWidget(double fixScale, TerminalDetailListItemBean itemBean){
    BoxFit boxFit = BoxFit.contain;
    int width = 1;
    int height = 1;
    String picsize = itemBean?.picList[0].picsize;
    String picurl = itemBean?.picList[0].getPicUrl();
    if (StringUtils.isNotEmpty(picsize)) {
      width = int.parse(picsize?.split("*")[0]);
      height = int.parse(picsize?.split("*")[1]);
    }
    double scale = width / height;
    if (fixScale > scale) {
      boxFit = BoxFit.cover;
    } else {
      boxFit = BoxFit.contain;
    }
    return VgCacheNetWorkImage(
      picurl ?? "",
      fit: boxFit,
      imageQualityType: ImageQualityType.middleDown,
    );
  }

  ///2图
  Widget _toTwoImageWidget(double containerWidth, double containerHeight, TerminalDetailListItemBean itemBean){
    String picurl1 = itemBean?.picList[0].getPicUrl();
    String picurl2 = itemBean?.picList[1].getPicUrl();

    return Column(
      children: [
        Expanded(
          child: VgCacheNetWorkImage(
            picurl1 ?? "",
            width: containerWidth,
            height: (containerHeight - 2)/2,
            fit: BoxFit.cover,
            imageQualityType: ImageQualityType.middleDown,
          ),
        ),
        Container(
          height: 2,
          color: Colors.white,
        ),
        Expanded(
          child: VgCacheNetWorkImage(
            picurl2 ?? "",
            width: containerWidth,
            height: (containerHeight - 2)/2,
            fit: BoxFit.cover,
            imageQualityType: ImageQualityType.middleDown,
          ),
        ),
      ],
    );
  }

  ///3图
  Widget _toThreeImageWidget(double containerWidth, double containerHeight, TerminalDetailListItemBean itemBean){
    String picurl1 = itemBean?.picList[0].getPicUrl();
    String picurl2 = itemBean?.picList[1].getPicUrl();
    String picurl3 = itemBean?.picList[2].getPicUrl();
    return Column(
      children: [
        Expanded(
          child: Row(
            children: [
              Expanded(
                child: VgCacheNetWorkImage(
                  picurl1 ?? "",
                  width: (containerWidth - 2)/2,
                  height: (containerHeight - 2)/2,
                  fit: BoxFit.cover,
                  imageQualityType: ImageQualityType.middleDown,
                ),
              ),
              Container(
                width: 2,
                color: Colors.white,
              ),
              Expanded(
                child: VgCacheNetWorkImage(
                  picurl2 ?? "",
                  width: (containerWidth - 2)/2,
                  height: (containerHeight - 2)/2,
                  fit: BoxFit.cover,
                  imageQualityType: ImageQualityType.middleDown,
                ),
              ),
            ],
          ),
        ),
        Container(
          height: 2,
          color: Colors.white,
        ),
        Expanded(
          child: VgCacheNetWorkImage(
            picurl3 ?? "",
            width: containerWidth,
            height: (containerHeight - 2)/2,
            fit: BoxFit.cover,
            imageQualityType: ImageQualityType.middleDown,
          ),
        ),
      ],
    );
  }

  ///4图及以上
  Widget _toFourImageWidget(double containerWidth, double containerHeight, TerminalDetailListItemBean itemBean){
    String picurl1 = itemBean?.picList[0].getPicUrl();
    String picurl2 = itemBean?.picList[1].getPicUrl();
    String picurl3 = itemBean?.picList[2].getPicUrl();
    String picurl4 = itemBean?.picList[3].getPicUrl();
    return Column(
      children: [
        Expanded(
          child: Row(
            children: [
              Expanded(
                child: VgCacheNetWorkImage(
                  picurl1 ?? "",
                  width: (containerWidth - 2)/2,
                  height: (containerHeight - 2)/2,
                  fit: BoxFit.cover,
                  imageQualityType: ImageQualityType.middleDown,
                ),
              ),
              Container(
                width: 2,
                color: Colors.white,
              ),
              Expanded(
                child: VgCacheNetWorkImage(
                  picurl2 ?? "",
                  width: (containerWidth - 2)/2,
                  height: (containerHeight - 2)/2,
                  fit: BoxFit.cover,
                  imageQualityType: ImageQualityType.middleDown,
                ),
              ),
            ],
          ),
        ),
        Container(
          height: 2,
          color: Colors.white,
        ),
        Expanded(
          child: Row(
            children: [
              Expanded(
                child: VgCacheNetWorkImage(
                  picurl3 ?? "",
                  width: (containerWidth - 2)/2,
                  height: (containerHeight - 2)/2,
                  fit: BoxFit.cover,
                  imageQualityType: ImageQualityType.middleDown,
                ),
              ),
              Container(
                width: 2,
                color: Colors.white,
              ),
              Expanded(
                child: VgCacheNetWorkImage(
                  picurl4 ?? "",
                  width: (containerWidth - 2)/2,
                  height: (containerHeight - 2)/2,
                  fit: BoxFit.cover,
                  imageQualityType: ImageQualityType.middleDown,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Map<String, ValueChanged> _getMenuMap(BuildContext context,
      TerminalDetailListItemBean itemBean) {
    if(itemBean.isSmart()){
      return {
        "取消播放": (_) {
          _onDeleteTap(itemBean);
        },
      };
    }
    if(itemBean.isIndex()){
      return {
        "取消播放": (_) {
          _onDeleteTap(itemBean);
        },
        "删除文件": (_) {
          _onDeleteForver(itemBean);
        }
      };
    }
    return {
      "重命名": (_) {
        _onUpdateName(itemBean);
      },
      "取消播放": (_) {
        _onDeleteTap(itemBean);
      },
      "删除文件": (_) {
        _onDeleteForver(itemBean);
      }
    };
  }



  _onTap(TerminalDetailListItemBean itemBean) {
    if (itemBean.isSmart()) {
      // SmartHomeOneDetailsPage.navigatorPush(context, itemBean?.shid, "", itemBean?.name, itemBean?.logo);
      SmartHomeStoreDetailsPage.navigatorPush(context, itemBean?.shid, "", itemBean?.name, itemBean?.logo);
    } else if(itemBean.isIndex()){
      BuildingIndexDiyBean buildingIndexBean = new BuildingIndexDiyBean();
      buildingIndexBean.id = itemBean?.comwid;
      BuildingIndexDiyDetailPage.navigatorPush(context, buildingIndexBean, false);
    }else if(itemBean.isHtml()){
      PosterDetailPage.navigatorPush(context, itemBean.htmlurl, itemBean.id,
          itemBean.likeflg, itemBean.cretype,
          _hsn, false, itemBean.logoflg, itemBean.addressflg, itemBean.diyflg, "01",
          itemBean.addressdiy, itemBean.namediy, itemBean.logodiy,
          itemBean.splpicurl, itemBean.pictype,
          position: widget?.position??"",
          cbid: widget?.cbid??"");
    }else{
      MediaDetailPage.navigatorPush(context, itemBean?.picid, "01", id: itemBean?.id, branchname: widget?.position??"");
    }
  }

  _onDeleteTap(TerminalDetailListItemBean itemBean) async{
    if(itemBean.isIndex()){
      bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
          title: "提示",
          content: "仅在当前终端显示屏取消播放，确认不再播放？",
          cancelText: "取消",
          confirmText: "确定",
          confirmBgColor:
          ThemeRepository.getInstance().getMinorRedColor_F95355());
      if (result ?? false) {
        VgEventBus.global.send(new UpdateHomePageEventMonitor());
        _viewModel.deleteTerminalBuildingIndex(context, widget?.hsn, itemBean?.buildingIndexId);
      }
      return;
    }
    ///智能家居删除
    if(itemBean.isSmart()){
      bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
          title: "提示",
          content: "仅在当前终端显示屏取消播放，确认不再播放？",
          cancelText: "取消",
          confirmText: "确定",
          confirmBgColor:
          ThemeRepository.getInstance().getMinorRedColor_F95355());
      if (result ?? false) {
        VgEventBus.global.send(new UpdateHomePageEventMonitor());
        _viewModel.deleteSmartHome(context, itemBean?.shid, widget?.hsn);
      }
      return;
    }
    if (StringUtils.isEmpty(itemBean?.picid)) {
      VgToastUtils.toast(context, "资源获取失败");
      return;
    }
    bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
        title: "提示",
        content: "仅在当前终端显示屏取消播放，确认不再播放？",
        cancelText: "取消",
        confirmText: "确定",
        confirmBgColor:
        ThemeRepository.getInstance().getMinorRedColor_F95355());
    if (result ?? false) {
      if("09" == (itemBean?.pictype??"")){
        //删除合成海报
        _viewModel.deleteComposePoster(context, widget?.hsn, itemBean?.picid, "01", itemBean?.splpicurl);
      }else if("01" == (itemBean?.uploadflg??"")){
        //删除推送海报
        _viewModel.deleteTodayPushPoster(context, widget?.hsn, itemBean?.picid);
      }else{
        _viewModel?.deleteFolder(context, itemBean.picid);
      }
    }
  }

  void _onDeleteForver(TerminalDetailListItemBean itemBean) async {
    if(itemBean.isIndex()){
      bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
          title: "提示",
          content: "所有终端显示屏中该文件都会删除，且不可找回，确认继续？",
          cancelText: "取消",
          confirmText: "删除",
          confirmBgColor:
          ThemeRepository.getInstance().getMinorRedColor_F95355());
      if (result ?? false) {
        VgEventBus.global.send(new UpdateHomePageEventMonitor());
        _viewModel.foreverDeleteTerminalBuildingIndex(context, itemBean?.comwid);
      }
      return;
    }
    if (StringUtils.isEmpty(itemBean?.picid)) {
      VgToastUtils.toast(context, "资源获取失败");
      return;
    }
    bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
        title: "提示",
        content: "所有终端显示屏中该文件都会删除，且不可找回，确认继续？",
        cancelText: "取消",
        confirmText: "删除",
        confirmBgColor:
        ThemeRepository.getInstance().getMinorRedColor_F95355());
    if (result ?? false) {
      _viewModel?.deleteForeverFolder(context, itemBean.picid, itemBean?.videoid, itemBean?.getToDeletePicUrl(), (itemBean?.isVideo()??false)?(itemBean?.picurl??""):"");
    }
  }

  void _onUpdateName(TerminalDetailListItemBean itemBean) {
    if (StringUtils.isEmpty(itemBean?.id)) {
      VgToastUtils.toast(context, "资源获取失败");
      return;
    }
    CommonEditWithTitleDialog.navigatorPushDialog(context,
        title: "重命名",
        confirmText: "确定",
        oldContent: itemBean.picname,
        onConfirm: (String content, VoidCallback popCallBack) {
          if (StringUtils.isEmpty(content)) {
            VgToastUtils.toast(context, "文件名不能为空");
            return;
          }
          VgToolUtils.removeAllFocus(context);
          _viewModel?.updateFolderName(
              context, itemBean?.picid, content, popCallBack);
        });
  }

  @override
  void loading(bool show, {String msg}) {
    ///有更新请求更新
    if (StringUtils.isNotEmpty(_jumpToFolderId)) {
      _jumpToFolderIdValueNotifier.value = _jumpToFolderId;
      _jumpToFolderId = null;
    }
    super.loading(show, msg: msg);
  }
}
